package com.zmn.oms.admin.controller.order;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto.LayuiTableResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.math.MoneyUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.office.excel.ExportExcelBuilder;
import com.zmn.oms.admin.controller.OmsBaseController;
import com.zmn.oms.common.constant.DefaultChannelListConsts;
import com.zmn.oms.common.constant.EntrustOrderConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.vo.KVDict;
import com.zmn.oms.model.dto.entrust.EntrustOrderDetailDTO;
import com.zmn.oms.model.dto.entrust.NewEntrustOrderDTO;
import com.zmn.oms.model.entity.entrust.EntrustOrderQuery;
import com.zmn.oms.model.vo.work.ZsNormalUpdateOrderVO;
import com.zmn.oms.model.vo.work.ZsOrderWorkVO;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkScheduleBService;
import com.zmn.oms.zmn.facade.interfaces.entrust.EntrustOrderFacade;
import io.shardingsphere.api.HintManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 类描述：
 *
 * @author lhl
 * @date 2020/01/14 17:45
 */
@Controller
@RequestMapping("/order/entrust")
public class EntrustOrderController extends OmsBaseController {

    @Autowired
    private EntrustOrderFacade entrustOrderFacade;
    @Autowired
    private ZsOrderWorkScheduleBService zsOrderWorkScheduleBService;

    private static final Map<String, String> SHEET_COLUMNS_NAME_MAP = Maps.newLinkedHashMap();
    static {
        SHEET_COLUMNS_NAME_MAP.put("orderId", "订单号");
        SHEET_COLUMNS_NAME_MAP.put("outerId", "服务商订单号");
        SHEET_COLUMNS_NAME_MAP.put("receiveTime", "下单时间");
        SHEET_COLUMNS_NAME_MAP.put("username", "姓名");
        SHEET_COLUMNS_NAME_MAP.put("userPhoneCallback", "用户电话");
        SHEET_COLUMNS_NAME_MAP.put("cityName", "城市");
        SHEET_COLUMNS_NAME_MAP.put("addressCallback", "地址");
        SHEET_COLUMNS_NAME_MAP.put("productInfo", "维修内容");
        SHEET_COLUMNS_NAME_MAP.put("statusName", "状态");
        SHEET_COLUMNS_NAME_MAP.put("totalAmountCallback", "订单金额");
        SHEET_COLUMNS_NAME_MAP.put("masterName", "工程师");
        SHEET_COLUMNS_NAME_MAP.put("masterPhoneCallback", "工程师电话");
        SHEET_COLUMNS_NAME_MAP.put("currentRemark", "下单备注");
        SHEET_COLUMNS_NAME_MAP.put("creater", "录入人");
        SHEET_COLUMNS_NAME_MAP.put("deptName", "录入部门");
    }

    /**
     * 新增订单
     *
     * @return
     */
    @RequestMapping(value = "add")
    public ModelAndView add() {
        return createNormalOrderModelAndView("order/entrustAdd", GlobalConsts.PLAT_MARK_ZMN);
    }

    /**
     * 新增普通单
     *
     * @return
     */
    @SuppressWarnings("all")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO saveOrder(@RequestBody @Valid NewEntrustOrderDTO order) {
        try {
            logger.debug("新增委托单：{}", JSON.toJSONString(order));

            ResultDTO resultDTO = entrustOrderFacade.insertOrder(order);

            logger.debug("新增委托单结果：{}", JSON.toJSONString(resultDTO));

            return resultDTO;
        } catch (OmsBaseException ex) {
            return ResultDTO.fail(ex.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultDTO.fail(e.getMessage());
        }
    }

    @RequestMapping(value = "/list")
    public ModelAndView list( ModelAndView mv) {
        mv.setViewName("entrust/work/list");
        // 下单日期
        mv.addObject("createTimeBegin", DateUtil.dateFormatToString(
                DateUtil.getMonthFirstDay(DateUtil.getNow()), DateUtil.FORMAT_DEFAULT, DateUtil.FORMAT_DATE));
        mv.addObject("createTimeEnd",
                DateUtil.toString(DateUtil.addDays(DateUtil.getNow(), 1), DateUtil.FORMAT_DATE));

        // 城市ID
        mv.addObject("cityList", super.getCityListByDept());
        // 状态
        mv.addObject("statusList", OrderStatusConsts.getOrderStatusList());
        return mv;
    }

    /**
     * 查询委托单列表 ajax
     */
    @PostMapping(value = "/ajax/list")
    @ResponseBody
    public ResultDTO ajaxList(@RequestBody EntrustOrderQuery query) {
        try {
            logger.debug("查询委托单：{}", JSON.toJSONString(query));

            processQuery(query);
            ResultDTO<List<ZsOrderWorkVO>> resultDTO = entrustOrderFacade.listOrders(query);
            LayuiTableResponseDTO data = LayuiTableResponseDTO.success(query.getTotalCount(), resultDTO.getData());

            logger.debug("查询委托单结果：{}", JSON.toJSONString(resultDTO));

            return ResultDTO.success(data);
        } catch (OmsBaseException ex) {
            return ResultDTO.fail(ex.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultDTO.fail(e.getMessage());
        }
    }

    /**
     * 委托单详情
     */
    @RequestMapping(value = "/detail")
    public ModelAndView detail(Long entrustId) {
        ModelAndView mv = new ModelAndView("entrust/work/detail");
        try (HintManager hintManager = HintManager.getInstance()) {
            hintManager.setMasterRouteOnly();
            ResultDTO<EntrustOrderDetailDTO> resultDTO = null;
            try {
                resultDTO = entrustOrderFacade.detail(entrustId);
            } catch (OmsBaseException e) {
                logger.error(e.getMessage(), e);
            }
            if (resultDTO != null && resultDTO.getData() != null) {
                EntrustOrderDetailDTO entrustOrderDetailDTO = resultDTO.getData();
                mv.addObject("entrustOrder", entrustOrderDetailDTO.getEntrustOrder());
                mv.addObject("entrustOrderSyncLogs", entrustOrderDetailDTO.getEntrustOrderSyncLogs());
            }
        }
        return mv;
    }

    /**
     * 创建普通工单的视图
     *
     * @param viewName 视图名称
     * @return
     */
    @SuppressWarnings("all")
    private ModelAndView createNormalOrderModelAndView(String viewName, int plat) {
        ModelAndView mav = new ModelAndView(viewName);

        // 性别
        mav.addObject("gender", super.dictModel2KVDict(GlobalDict.getGenderList()));
        // 订单类型
        //mav.addObject("type", super.dictModel2KVDict(OrderConsts.getOrderTypeList()));
        // 渠道列表 1不禁用，2禁用
        //KVDict<Integer> channel_myx = new KVDict<>(900001, "蚂蚁修", false);
        mav.addObject("channelList", super.getChannelListByDept(plat));
        // 服务分类
        KVDict<Integer> servCateg_repair = KVDict.<Integer>builder().value(GlobalConsts.SERV_CATEG_REPAIR)
                .text(GlobalConsts.getServCategName(GlobalConsts.SERV_CATEG_REPAIR)).disabled(false).build();
        mav.addObject("servCategList", Lists.newArrayList(servCateg_repair));
        // 产品
        //KVDict<Integer> product_phone = new KVDict<>(20553, "手机维修", false);
        mav.addObject("servProductList", EntrustOrderConsts.getProductList());
        // 产品分类
        KVDict<Integer> productShowType = KVDict.<Integer>builder().value(GlobalConsts.NO)
                .text("后台产品").disabled(false).build();
        mav.addObject("productShowType", Lists.newArrayList(productShowType));
        // 省份
        mav.addObject("provinceList", super.getAllProvinceList());
        // 城市ID
        mav.addObject("cityList", super.getAllCityList());

        ZsNormalUpdateOrderVO zsNormalUpdateOrderVO = new ZsNormalUpdateOrderVO();
        zsNormalUpdateOrderVO.setBizType(com.zmn.consts.GlobalConsts.BIZ_TYPE_C);
        zsNormalUpdateOrderVO.setPlatWork(plat);
        zsNormalUpdateOrderVO.setPlat(plat);
        zsNormalUpdateOrderVO.setGender(GlobalDict.GENDER_NO);
        //zsNormalUpdateOrderVO.setChannelId(channel_myx.getValue());
        zsNormalUpdateOrderVO.setServCategId(GlobalConsts.SERV_CATEG_REPAIR);
        zsNormalUpdateOrderVO.setProductShowType(GlobalConsts.NO);
        mav.addObject("orderInfo", zsNormalUpdateOrderVO);

        return mav;
    }

    /**
     * 信息导出
     * @param query
     * @param response
     * @throws Exception
     */
    @GetMapping(value = "/export")
    public void export(EntrustOrderQuery query, HttpServletResponse response) throws Exception {
        logger.debug("导出委托单：{}", JSON.toJSONString(query));

        query.setPageSize(5000);
        processQuery(query);
        List<ZsOrderWorkVO> list = entrustOrderFacade.listOrders(query).getData();

        ExportExcelBuilder excelBuilder = new ExportExcelBuilder();
        ExportExcelBuilder.ExcelSheet<ZsOrderWorkVO> sheet1 = excelBuilder.createExcelSheet("委派单信息",
                list, SHEET_COLUMNS_NAME_MAP, true);

        sheet1.setCallback((fieldName, entity) -> {
            // 用户手机号，隐藏中间4位
            if ("userPhoneCallback".equals(fieldName)) {
                String userPhone = entity.getUserPhone();
                if (StringUtils.isNotBlank(userPhone)) {
                    int len = userPhone.length();
                    String head = (len > 8) ? userPhone.substring(0, len-8) : "";
                    String end = (len >= 5) ? userPhone.substring(len-5, len-1) : userPhone;
                    userPhone = String.format("%s****%s", head, end);
                }
                return userPhone;
            }
            // 师傅手机号，隐藏中间4位
            else if ("masterPhoneCallback".equals(fieldName)) {
                String userPhone = entity.getMasterPhone();
                if (StringUtils.isNotBlank(userPhone)) {
                    int len = userPhone.length();
                    String head = (len > 8) ? userPhone.substring(0, len-8) : "";
                    String end = (len >= 5) ? userPhone.substring(len-5, len-1) : userPhone;
                    userPhone = String.format("%s****%s", head, end);
                }
                return userPhone;
            }
            else if ("addressCallback".equals(fieldName)) {
                String userStreet = Optional.ofNullable(entity.getUserStreet()).orElse("");
                String userAddress = Optional.ofNullable(entity.getUserAddress()).orElse("");
                return userStreet + userAddress;
            }
            else if ("totalAmountCallback".equals(fieldName)) {
                Integer totalAmount = entity.getTotalAmount();
                if (NumberUtil.isNotNullOrZero(totalAmount)) {
                    return MoneyUtil.parseToYuanStr(totalAmount);
                }
                return null;
            }

            return null;
        });
        sheet1.builderData();


        excelBuilder.exportExcel(response, "委派单管理");
    }

    /**
     * 解析查询参数
     * @param query
     */
    private void processQuery(EntrustOrderQuery query) {
        // 下单时间
        if (StringUtils.isNotBlank(query.getReceiveTime())) {
            String receiveTimeStr = query.getReceiveTime();
            String[] arr = receiveTimeStr.split(",");
            String strBegin = null;
            String strEnd = null;

            if (arr.length == 1) {
                if (receiveTimeStr.endsWith(",")) {
                    strBegin = arr[0];
                }
                else {
                    strEnd = arr[0];
                }
            }
            else if (arr.length == 2) {
                strBegin = arr[0];
                strEnd = arr[1];
            }

            if ((StringUtils.isNotBlank(strBegin))) {
                query.setCreateTimeBegin(DateUtil.parse(strBegin));
            }
            if ((StringUtils.isNotBlank(strEnd))) {
                query.setCreateTimeEnd(DateUtil.parse(strEnd));
            }
        }
    }
}
